package com.jftone.bh.app.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.jftone.bh.app.config.SysConst;
import com.jftone.bh.app.directive.FuncOperDirective;
import com.jftone.bh.app.directive.PageDirective;
import com.jftone.bh.app.model.SysAdmin;
import com.jftone.bh.app.model.SysAdminRole;
import com.jftone.bh.app.service.OSSFileManagerService;
import com.jftone.bh.app.service.SysRoleService;
import com.jftone.bh.app.util.UploadFile;
import com.jftone.bh.app.util.UploadFile.FileDir;
import com.jftone.bh.app.util.UploadFile.State;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jftone.action.ActionSupport;
import org.jftone.component.BeanContext;
import org.jftone.config.Const;
import org.jftone.exception.ActionException;
import org.jftone.util.DataMap;
import org.jftone.util.DateUtil;
import org.jftone.util.IData;
import org.jftone.util.StringUtil;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class BaseAction extends ActionSupport {
	private Log log = LogFactory.getLog(BaseAction.class);
	private StringBuilder builder = new StringBuilder();


	/**
	 * 判断是否已经登录
	 * @return
	 */
	public boolean isLogin(){
		HttpSession session = getRequest().getSession(false);
		boolean flag = false;
		if(session!= null && session.getAttribute(SysConst.ADMIN_USER) != null){
			 flag = true;
		}
		return flag;
	}
	
	/**
	 * 用户Session数据
	 * @throws ActionException 
	 */
	public IData<String, Object> getSessionData(SysAdmin admin) throws ActionException{
		IData<String, Object> data = new DataMap<String, Object>();
		data.put("id", admin.getId());
		data.put("adminUser", admin.getAdminUser());
		data.put("userName", admin.getUserName());
		data.put("mobile", admin.getMobile());
		data.put("email", admin.getEmail());
		try{
			SysRoleService service = BeanContext.getBean(SysRoleService.class);
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("userNo", admin.getAdminUser());
			List<SysAdminRole> sarList = service.querySysAdminRole(inData);
			if(null != sarList && sarList.size()>0){
				List<String> list = new ArrayList<String>();
				for(SysAdminRole obj : sarList){
					list.add(obj.getRoleCode());
				}
				data.put("roleCode", StringUtil.join(list.toArray(), ","));
			}
		}catch (Exception e) {
			throw new ActionException("获取角色数据错误", e);
		}
		return data;
	}
	
	/**
	 * 设置页面查询跳转需要带入的参数
	 * @param key
	 * @param value
	 */
	public BaseAction putParam(String key, Object value){
		builder.append("&"+ key + "="+ value);
		return this;
	}
	/**
	 * 返回页面查询跳转需要带入的参数
	 * @return
	 */
	public String getParam(){
		return builder.toString();
	}
	
	
	/**
	 * 系统操作提示
	 * 一般在数据更新，删除等操作后使用
	 * @param titleMsg
	 * @param actionUrl
	 * @throws ActionException
	 */
	public void showMsg(String titleMsg, String actionUrl) throws ActionException {
	    putRenderInfo("msg", titleMsg);
	    putRenderInfo("url", actionUrl);
		render("common/success.html");
	}

	/**
	 * 告警提示框，点击进行js返回
	 * @param alertMsgs
	 * @throws ActionException
	 */
	public void alertMsg(List<String> alertMsgs) throws ActionException {
		putRenderInfo("msgList", alertMsgs);
		render("common/alert.html");
	}
	public void alertMsg(String alertMsg) throws ActionException {
		List<String> list = new ArrayList<String>();
		list.add(alertMsg);
		alertMsg(list);
	}
	
	/**
	 * 渲染错误页面模板
	 * @param titleMsg
	 * @param content
	 * @param detail
	 * @param actionUrl
	 */
	public void errorMsg(String titleMsg, String content, String detail, String actionUrl) {
		this.putRenderInfo("title", titleMsg);
		this.putRenderInfo("content", content);
		this.putRenderInfo("detail", detail);
		this.putRenderInfo("url", actionUrl);
		try {
			render("common/error.html");
		} catch (ActionException e) {
			log.error("页面渲染错误", e);
		}
	}
	
	/**
	 * 登录超时提示
	 */
	public void loginTimeoutMsg() {
		try {
			render("common/login_timeout.html");
		} catch (ActionException e) {
			log.error("页面渲染错误", e);
		}
	}
	
	/**
	 * 发送页面输出数据
	 * @param resultCode
	 * @param resultMsg
	 * @throws IOException
	 */
	public void send(int resultCode, String resultMsg) throws ActionException{
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"resultCode\":"+resultCode+"");
		sb.append(", \"resultMsg\":\""+resultMsg+"\"");
		sb.append("}");
		this.send(sb.toString(), Const.CONTENT_TEXT);
	}
	public void send(int resultCode, String resultMsg, Object resultData) throws ActionException{
		String jsonStr = "{}";
		if(resultData.getClass().isArray() || resultData instanceof List){
			jsonStr = JSONArray.fromObject(resultData).toString();
		}else{
			jsonStr = JSONObject.fromObject(resultData).toString();
		}
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"resultCode\":"+resultCode+"");
		sb.append(", \"resultMsg\":\""+resultMsg+"\"");
		sb.append(", \"resultData\":" + jsonStr);
		sb.append("}");
		this.send(sb.toString(), Const.CONTENT_TEXT);
	}
	public void send(Object resultData) throws ActionException{
		String jsonStr = "{}";
		if(resultData.getClass().isArray() || resultData instanceof List){
			jsonStr = JSONArray.fromObject(resultData).toString();
		}else{
			jsonStr = JSONObject.fromObject(resultData).toString();
		}
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"resultCode\":0");
		sb.append(", \"resultData\":" + jsonStr);
		sb.append("}");
		this.send(sb.toString(), Const.CONTENT_TEXT);
	}
	
	/**
	 * 获取权限编码
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getRightCode() {
		HttpSession session = getRequest().getSession(false);
		if(session == null || session.getAttribute(SysConst.RIGHT_CODE) == null){
			 return "";
		}
		Map<String, String> rcMap = (Map<String, String>)session.getAttribute(SysConst.RIGHT_CODE);
		return rcMap.get(getClass().getSimpleName()+"."+getCurActionMethod());
	}
	
	//菜单功能指令
	@SuppressWarnings("unchecked")
	public void setMenuFuncDerictive() {
		HttpSession session = this.getRequest().getSession();
		IData<String, Object> admin = (IData<String, Object>)session.getAttribute(SysConst.ADMIN_USER);
		this.putRenderInfo(SysConst.MENU_FUNC_DERICTIVE, new FuncOperDirective(admin.getString("roleCode", ""), getRightCode()));
	}
	//分页指令
	public void setPageDerictive() {
		this.putRenderInfo(SysConst.PAGE_DERICTIVE, new PageDirective(getPage()));
	}



	/**
	 *
	 * @param fileNamePrefix  文件名前缀
	 * @param fileDir 预定义的上传路径
	 * @param fileMaxSize 最大文件大小
	 * @param sizeThreshold 默认为10k
	 * @param redirectUrl 重定向url
	 * @throws ActionException
	 */
	public void upload(String fileNamePrefix, FileDir fileDir, long fileMaxSize, int sizeThreshold, String redirectUrl) throws ActionException {
		HttpServletRequest request = getRequest();
		UploadFile up = new UploadFile();
		try {
			if(!ServletFileUpload.isMultipartContent(request)){
				throw new Exception("非文件上传请求");
			}
			if(sizeThreshold<100)sizeThreshold = 10 * 1024;

			DiskFileItemFactory factory= new DiskFileItemFactory();
			factory.setSizeThreshold((int)fileMaxSize);	  //默认10K
			factory.setRepository(up.makeDirectory());
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding(Const.CHARSET_UTF8);
			upload.setFileSizeMax(fileMaxSize);		//最大文件大小

			IData<String, String> data = new DataMap<String, String>();
			FileItem fileItem = null;
			List<FileItem> listItem = upload.parseRequest(request);
			for (FileItem item : listItem) {
				if(item.isFormField()){
					data.put(item.getFieldName(), item.getString(Const.CHARSET_UTF8));
				}else{
					fileItem = item;
				}
			}
			String dir = null;
			short imgType = data.getShort("imgType");
			if(imgType == fileDir.getImgType()){
				dir = fileDir.getDir();
			}
			String imgSrc = null;
			String pathSuffix = "/" + DateUtil.getNowStr("yyMM");

			if(fileItem.getSize() > 0) {
				String name = fileItem.getName();
				String fileExtension = name.substring(name.lastIndexOf(".")+1).toLowerCase();
				if(UploadFile.FILE_TYPE.indexOf(fileExtension)<0){
					putParam("resultCode", State.NO_SUPPORT_EXTENSION.getCode());
					putParam("resultMsg", State.NO_SUPPORT_EXTENSION.getMessage());
					return;
				}
				imgSrc = fileNamePrefix + "." + fileExtension;
				String fileUrl =  BeanContext.getBean(OSSFileManagerService.class).upload(fileItem.getInputStream(),dir+pathSuffix,imgSrc);
				putParam("fileUrl", fileUrl);
			}

			String imgURI = dir + pathSuffix +"/"+ imgSrc;
			long imgId = up.getTmpImgId(imgType, imgURI);
			putParam("resultCode", State.OK.getCode());
			putParam("resultMsg", State.OK.getMessage());
			putParam("imgId", imgId);
			putParam("imgSrc", imgURI);
		}catch(FileUploadException e) {
			putParam("resultCode", State.OVER_FILE_LIMIT.getCode());
			putParam("resultMsg", State.OVER_FILE_LIMIT.getMessage());
			log.error("上传文件错误"+fileDir.getDir()+e.getMessage(), e);
		}catch (Exception e) {
			putParam("resultCode", State.ERROR.getCode());
			putParam("resultMsg", State.ERROR.getMessage());
			log.error("上传文件错误" + fileDir.getDir()+ e.getMessage(), e);
		}finally{
			this.redirect(redirectUrl+getParam());
		}
	}
}

